/*
 * @(#)SingleThreadExecutor.java 1.0 2014/02/14
 *
 * Copyright (c) 2014 SinoSoft Refactored by filon51.
 * All rights reserved.
 *
 */
package com.sinosoft.cloud.dp.thread;

import org.apache.log4j.Logger;

import java.util.HashMap;

/**
 * 单线程执行引擎
 *
 * @author filon51
 * @since 2014-02-14
 */
public class SingleThreadExecutor implements ThreadExecutor {
	private Logger m_log = Logger.getLogger(SingleThreadExecutor.class);

	public SingleThreadExecutor() {
		// do nothing
	}

	public void executeService(BusinessService businessService) {
		if (businessService == null) {
			m_log.fatal("parameter BusinessService can't be null");
			return;
		}
		m_log.info("BusinessService start");

		businessService.onInitialiseResource();
		businessService.prepareElement();

		HashMap hashElement = null;
		HashMap hashResult = null;
		int count = 0;
		try {
			while (businessService.hasMoreElement()) {
				count++;
				hashElement = businessService.nextElement();
				hashResult = businessService.processOneElement(hashElement);
				businessService.saveOneElement(hashResult);
			}
			m_log.info("total deal count == " + count);
			businessService.flushAllElements();
		} catch (Exception ex) {
			m_log.error("Exception Occured! total deal count == " + count);
			ex.printStackTrace();
			businessService.dealException();
		} finally {
			businessService.onReleaseResource();
		}
		m_log.info("BusinessService end");
	}
}
